/**
 * Created by henian.xu on 2018/7/14.
 * 指令注册
 */

/*function hasPowerOld(dataMap, { value, modifiers }) {
    if (!dataMap || dataMap['*']) return true;
    let res = false;
    for (let i = 0, item; (item = value[i++]); ) {
        res = false;
        const itemArr = item.split(':');
        let obj = dataMap;
        for (let index = 0, name; (name = itemArr[index++]); ) {
            if (!obj[name]) break;
            obj = obj[name];
            if (obj === true || obj['*'] === true) {
                res = true;
                break;
            }
        }

        if (modifiers['&&']) {
            if (!res) break;
        } else {
            if (res) break;
        }
    }
    return res;
}*/
function hasPower(dataMap, { value, modifiers }) {
    if (!dataMap || dataMap['*']) return true;
    let res = false;
    for (let i = 0, item; (item = value[i++]); ) {
        res = !!dataMap[item];
        if (!res) {
            const itemArr = item.split(':');
            const itemLng = itemArr.length - 1;
            for (let n = 0; n < itemLng; n++) {
                itemArr.length--;
                const key = itemArr.join(':') + ':*';
                res = !!dataMap[key];
                if (res) break;
            }
        }
        if (modifiers['&&']) {
            if (!res) break;
        } else {
            if (res) break;
        }
    }
    return res;
}

export default {
    install(Vue, { store }) {
        Vue.directive('page-title', (el, binding) => {
            // 当绑定元素插入到 DOM 中。
            document.title = binding.value || '';
        });
        Vue.directive('power', {
            inserted(el, binding) {
                const dataMap = store.getters['global/power/dataMap'];
                const isPower = hasPower(dataMap, binding);
                // console.log(dataMap, isPower);
                if (isPower) return;
                const parentNode = el.parentNode;
                parentNode.removeChild(el);
            },
        });
    },
};
